package zz.app.jmhviewer;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import java.io.IOException;
import java.util.ArrayList;

import zz.app.jmhviewer.JMH.JMHJsonData;
import zz.app.jmhviewer.JMH.JMHUtils;

/**
 * Created by zz on 2018/1/31 21:47.
 */

public class GetJsonDataTask extends AsyncTask<String,Integer,Integer> {
    private Context context;
    private ProgressBar progressBar;
    private Dialog dialog;
    private ArrayList<JMHJsonData> dataArrayList;
    private MusicListAdapter adapter;
    private OnFinishedResultListener onFinishedResultListener;
    private boolean resultOK=false;

    public void setOnFinishedResultListener(OnFinishedResultListener onFinishedResultListener) {
        this.onFinishedResultListener = onFinishedResultListener;
    }

    public GetJsonDataTask(Context c, MusicListAdapter musicListAdapter){
        context=c;
        adapter=musicListAdapter;
    }
    @Override
    protected Integer doInBackground(String... strings) {
        try {
            dataArrayList= JMHUtils.getPlayList(strings[0]);
            if(dataArrayList.size()>0)resultOK=true;
            publishProgress(100);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog=new Dialog(context);
        dialog.addContentView(View.inflate(context,R.layout.waitview,null),new ViewGroup.LayoutParams(600,300));
        progressBar=dialog.findViewById(R.id.pbValue);
        progressBar.setProgress(0);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

    }

    @Override
    protected void onPostExecute(Integer o) {
        super.onPostExecute(o);
        if(dialog!=null&&dialog.isShowing()){
            dialog.dismiss();
        }
        adapter.setJsonData(dataArrayList);
        adapter.notifyDataSetChanged();
        if(onFinishedResultListener!=null){
            onFinishedResultListener.onFinishedResult(resultOK);
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);

    }
}
